package StudyCode.summary.zipfile;

import java.io.*;
import java.util.zip.GZIPInputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class GZIPDecompressesData {
	private static final int _BUFFER_SIZE = 1024;

	public static byte[] decompress(byte[] data) throws IOException,
			UnsupportedEncodingException {
		byte[] buffer = new byte[_BUFFER_SIZE];
		ByteArrayInputStream bais = null;
		GZIPInputStream gis = null;
		ByteArrayOutputStream baos = null;

		int byteRead = 0;
		try {
			bais = new ByteArrayInputStream(data);
			gis = new GZIPInputStream(bais);
			baos = new ByteArrayOutputStream();

			while ((byteRead = gis.read(buffer, 0, buffer.length)) != -1) {
				baos.write(buffer, 0, byteRead);
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		} finally {
			try {
				if (baos != null) {
					baos.close();
				}

				if (gis != null) {
					gis.close();
				}

				if (bais != null) {
					bais.close();
				}
			} catch (Exception exception) {
			}
		}
		return baos.toByteArray();
	}

	public static void decompress(InputStream inputStream,
	                              OutputStream outputStream) throws IOException {
		byte[] buffer = new byte[_BUFFER_SIZE];
		GZIPInputStream gis = null;

		try {
			gis = new GZIPInputStream(inputStream);

			int bytesRead = 0;
			while ((bytesRead = gis.read(buffer, 0, buffer.length)) != -1) {
				outputStream.write(buffer, 0, bytesRead);
			}
		} catch (IOException exception) {
			exception.printStackTrace();
			throw exception;
		} finally {
			if (gis != null) {
				gis.close();
			}
		}
	}

	public static void decompress(File inputFile, File outputFile)
			throws IOException {
		FileInputStream fis = null;
		FileOutputStream fos = null;

		try {
			fis = new FileInputStream(inputFile);
			fos = new FileOutputStream(outputFile);
			decompress(fis, fos);
		} catch (IOException exception) {
			throw exception;
		} finally {
			if (fis != null) {
				fis.close();
			}
			if (fos != null) {
				fos.close();
			}
		}
	}
}
